package org.piggy.core.netty;

import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.util.AttributeKey;
import org.piggy.common.constants.OtherConst;

public class WebsocketClientHandler extends SimpleChannelInboundHandler<Object> {

    private final WebSocketClientHandshaker shaker;

    public WebsocketClientHandler(WebSocketClientHandshaker shaker) {
        this.shaker = shaker;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        shaker.handshake(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel channel2 = ctx.channel();
        Channel channel1 = (Channel) channel2.attr(AttributeKey.valueOf(OtherConst.FUTURE_1)).get();
        channel1.close();
        channel2.close();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) {
        Channel channel = ctx.channel();

        if (!shaker.isHandshakeComplete()) {
            try {
                FullHttpResponse response = (FullHttpResponse) msg;
                shaker.finishHandshake(channel, response);
            } catch (WebSocketHandshakeException e) {
                e.printStackTrace();
            }
            return;
        }

        if(msg instanceof WebSocketFrame frame){
            Channel channel1 = (Channel) channel.attr(AttributeKey.valueOf(OtherConst.FUTURE_1)).get();
            frame.retain();
            channel1.writeAndFlush(frame);
        }
    }

}

